package okw.network;

import java.io.IOException;
import java.sql.Time;
import java.util.ArrayList;

import core.messages.Info;


public class Sender implements Runnable {

	private Queue queue = null;
	private Queue2 queue2 = null;
	
	public Sender(Queue queue, Queue2 queue2){
		this.queue = queue;
		this.queue2 = queue2;
	}
	
	public void run() {
		while(true){
			// szuka niewyslanych i wysla ponownie
			ArrayList<QueueItem> list = queue2.findToSend();
			if(list!=null){
				for(QueueItem e: list){
					try {
						System.out.println("WIADOMOSC PONOWNA DO, TYP, NR: " + e.getTerminal().getName() + " " + e.getMsg().getType() + " " + e.getMsg().getNumber());
						if(e!= null && e.getTerminal().getOos()!= null)
							e.getTerminal().getOos().writeObject(e.getMsg());
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
			
			// wyciaga element z kolejki i wrzuca na druga jesli nie jest ack. Dodajac czas wrzucenia
			QueueItem tmp = queue.get();
			if(tmp!= null && tmp.getTerminal().getOos()!= null){
				if(!tmp.getMsg().getType().equals("Potwierdzenie")){
					tmp.setTime(new Time(System.currentTimeMillis()));
					queue2.put(tmp);
				}
				try {
					if(tmp.getMsg().getClass().equals(Info.class)){
						Info o = (Info) tmp.getMsg();
						System.out.println(o.getStan());
					}
						
					tmp.getTerminal().getOos().writeObject(tmp.getMsg());
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else if(tmp!= null){
				System.out.println("DUUUPAAAA2");
				tmp.setTime(new Time(System.currentTimeMillis()));
				queue2.put(tmp);
			}
		}	
	}	
}
